<!--  -->
<template>
  <div>
    <el-form ref="formRef" label-position="top" :model="formData" :rules="rules">
      <el-form-item label="手机号码" prop="loginName">
        <el-input class="countryWrapper" v-model="formData.loginName" placeholder="请输入手机号码" clearable>
          <template #prefix>
            <country-code-selector :countryCode.sync="formData.countryCode" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!captcha">
        <el-input v-model="formData.password" placeholder="请输入密码" show-password clearable></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="validateCode" v-if="captcha">
        <div class="flex-btw w-full">
          <el-input class="captcha" v-model="formData.validateCode" placeholder="请输入验证码" clearable></el-input>
          <send-code class="sendCode" field="loginName" :params="{ phone: formData.loginName, type: 'USER_LOGIN' }" :elRef="formRef" />
        </div>
      </el-form-item>
      <div class="toggle flex-btw">
        <el-button type="text" size="small" @click="toggleMode('retrieve')">找回密码</el-button>
        <el-button type="text" size="small" @click="toggleFn">{{ captcha ? '密码登录' : '验证码登录' }}</el-button>
      </div>
    </el-form>
    <div class="btns">
      <div><el-button round class="bigBtn" type="primary" @click="onSubmit">立即登录</el-button></div>
      <div><el-button round class="bigBtn" @click="registerDialog">注册</el-button></div>
    </div>
  </div>
</template>

<script setup>
import { encryptData } from "@/utils/encrypt";
// 获取用户信息
const user = useStore.user()
const emit = defineEmits(['update','close']);

const formData = reactive({
  loginName:'',
  password: '',
  captchaCode: "string",
  captchaUuid: "string"
})
const rules = {
  loginName: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  validateCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}
const captcha = ref(false)

const toggleFn = () => {
  captcha.value = !captcha.value
}

const toggleMode = (val) => {
  emit('update', val)
}

const formRef = ref()
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      user.loginApi({...formData,loginDevice:6, password: encryptData(formData.password) }).then(res=>{
        formRef.value.resetFields()
        emit('close')
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const registerDialog = ()=>{
  user.showRegister = true
  user.showLogin = false
}
</script>
<style lang='scss' scoped>
.captcha {
  flex: 1;
  margin-right: 10px;
}

.toggle {
  .el-button--text {
    color: var(--use-color-warning);
    font-size: 16px;
  }
}

.mt40 {
  margin-top: 40px;
}

.btns {
  >div {
    margin-top: 24px;
  }

  .el-button {
    width: 100%;
    border-radius: 56px !important;
  }
}

.sendCode{
  height: 56px;
  border-radius:28px;
}
</style>
